<template>
	<!-- 预约页面 -->
  <div>
    <van-tabs v-if="!showDeptDetail" v-model:active="mainTab">
      <van-tab title="挂号预约">
        <div class="dept-select-container">
          <!-- 左侧一级科室 -->
          <van-sidebar v-model="activeDeptIndex" class="sidebar">
            <van-sidebar-item
              v-for="(dept, idx) in departments"
              :key="dept.dept_id"
              :title="dept.name"
            />
          </van-sidebar>
          <!-- 右侧二级科室列表 -->
          <div class="subdept-panel">
            <van-cell
              v-for="second in departments[activeDeptIndex]?.children || []"
              :key="second.dept_id"
              :title="second.name"
              :label="second.introduction"
              is-link
              @click="onDeptDetail(second)"
            />
          </div>
        </div>
      </van-tab>
      <van-tab title="挂号管理">
        <!-- 订单状态筛选 -->
        <van-tabs v-model:active="orderTabActive" sticky>
          <van-tab title="待支付">
            <van-list v-model:loading="orderLoading" :finished="orderFinished" finished-text="没有更多了">
              <van-cell
                v-for="order in filteredOrders('待支付')"
                :key="order.id"
                :title="order.department + ' | ' + order.doctor"
                :label="`预计就诊：${order.visit_date} ${order.time_slot} | 预约时间：${order.create_time} | 费用：¥${order.price}`"
                @click="showOrderDetail(order)"
              >
                <template #right-icon>
                  <van-button size="small" type="danger" @click.stop="onCancel(order)">取消</van-button>
                  <van-button size="small" type="primary" @click.stop="onReschedule(order)">改期</van-button>
                </template>
              </van-cell>
            </van-list>
          </van-tab>
          <van-tab title="已支付">
            <van-list v-model:loading="orderLoading" :finished="orderFinished" finished-text="没有更多了">
              <van-cell
                v-for="order in filteredOrders('已支付')"
                :key="order.id"
                :title="order.department + ' | ' + order.doctor"
                :label="`预计就诊：${order.visit_date} ${order.time_slot} | 支付时间：${order.pay_time} | 费用：¥${order.price}`"
                @click="showOrderDetail(order)"
              >
                <template #right-icon>
                  <van-button size="small" type="danger" @click.stop="onCancel(order)">取消</van-button>
                  <van-button size="small" type="primary" @click.stop="onReschedule(order)">改期</van-button>
                </template>
              </van-cell>
            </van-list>
          </van-tab>
          <van-tab title="已完成">
            <van-list v-model:loading="orderLoading" :finished="orderFinished" finished-text="没有更多了">
              <van-cell
                v-for="order in filteredOrders('已完成')"
                :key="order.id"
                :title="order.department + ' | ' + order.doctor"
                :label="`预计就诊：${order.visit_date} ${order.time_slot} | 实际就诊：${order.actual_visit_time} | 费用：¥${order.price}`"
                @click="showOrderDetail(order)"
              >
                <template #right-icon>
                  <van-tag type="success">已完成</van-tag>
                </template>
              </van-cell>
            </van-list>
          </van-tab>
          <van-tab title="已取消">
            <van-list v-model:loading="orderLoading" :finished="orderFinished" finished-text="没有更多了">
              <van-cell
                v-for="order in filteredOrders('已取消')"
                :key="order.id"
                :title="order.department + ' | ' + order.doctor"
                :label="`原预计就诊：${order.visit_date} ${order.time_slot} | 取消时间：${order.cancel_time} | 费用：¥${order.price}`"
                @click="showOrderDetail(order)"
              >
                <template #right-icon>
                  <van-tag type="danger">已取消</van-tag>
                </template>
              </van-cell>
            </van-list>
          </van-tab>
        </van-tabs>
      </van-tab>
    </van-tabs>
    <van-popup v-model:show="showDeptDetail" position="right" :style="{ width: '100vw', height: '100%' }">
      <div v-if="!showDoctorDetailPage" class="dept-detail-panel">
        <van-nav-bar title="科室详情" left-text="返回" left-arrow @click-left="showDeptDetail = false" />
        <div class="dept-info">
          <div class="dept-title">{{ deptDetail.name }}</div>
          <div class="dept-desc">{{ deptDetail.introduction }}</div>
        </div>
        <!-- 日期选择，只显示一行横向日期 -->
        <div class="date-row-scroll">
          <div
            v-for="(date, idx) in weekDates"
            :key="date.value"
            class="date-item"
            :class="{ active: selectedDate === date.value, disabled: date.disabled }"
            @click="!date.disabled && (selectedDate = date.value)"
          >
            <div>{{ date.label }}</div>
            <div>{{ date.text }}</div>
          </div>
        </div>
        <!-- 筛选条件，上午-下午-只看有号横向紧凑排列 -->
        <div class="doctor-filter-row-compact">
          <van-radio-group v-model="filterTime" direction="horizontal" class="doctor-filter-radio">
            <van-radio name="上午">上午</van-radio>
            <van-radio name="下午">下午</van-radio>
          </van-radio-group>
          <van-checkbox v-model="onlyAvailable" class="doctor-filter-checkbox">只看有号</van-checkbox>
        </div>
        <!-- 医生列表 -->
        <van-list>
          <van-cell
            v-for="doc in filteredDoctorsWithSchedule"
            :key="doc.id"
            :title="doc.name + '（' + doc.title + '）'"
            :label="doc.specialty"
            @click="onDoctorDetailPage(doc)"
          >
            <template #icon>
              <van-image :src="doc.avatar" width="40" height="40" round />
            </template>
            <template #right-icon>
              <van-tag v-if="hasAvailableScheduleForDate(doc.id)" type="success" size="small">有号</van-tag>
              <van-tag v-else type="danger" size="small">无号</van-tag>
              <van-tag type="primary" size="small">查看排班</van-tag>
            </template>
          </van-cell>
        </van-list>
      </div>
      <div v-else class="doctor-detail-panel doctor-detail-nested">
        <van-nav-bar title="医生主页" left-text="返回" left-arrow @click-left="showDoctorDetailPage = false" />
        <div class="doctor-info-block">
          <van-image :src="doctorDetail.avatar" width="80" height="80" round class="doctor-avatar" />
          <div class="doctor-main-info">
            <div class="doctor-name">{{ doctorDetail.name }}</div>
            <div class="doctor-title">{{ doctorDetail.title }}</div>
            <div class="doctor-specialty">专长：{{ doctorDetail.specialty }}</div>
            <div class="doctor-visit">接诊量：{{ doctorDetail.visit_count }}</div>
          </div>
        </div>
        <van-divider>医生简介</van-divider>
        <div class="doctor-desc">{{ doctorDetail.desc }}</div>
        <van-divider>排班信息</van-divider>
        <div class="schedule-list">
          <van-cell
            v-for="schedule in filteredSchedules"
            :key="schedule.schedule_id"
            :title="formatScheduleDate(schedule.visit_date) + ' ' + formatTimeSlot(schedule.time_slot)"
            :label="`${schedule.start_time}-${schedule.end_time} | 剩余号源: ${schedule.remaining_quota} | 价格: ` + ''"
          >
            <template #label>
              <span>{{ schedule.start_time }}-{{ schedule.end_time }} | 剩余号源: {{ schedule.remaining_quota }} | 价格: <span class="schedule-price">¥{{ schedule.price }}</span></span>
            </template>
            <template #right-icon>
              <van-tag v-if="schedule.remaining_quota > 0" type="success" size="mini" class="schedule-available-tag">有号</van-tag>
              <van-tag v-else type="danger" size="mini" class="schedule-available-tag">无号</van-tag>
              <van-button size="normal" type="primary" class="schedule-appoint-btn" @click.stop="onScheduleSelect(schedule)">预约</van-button>
            </template>
          </van-cell>
        </div>
      </div>
    </van-popup>
    <!-- 订单详情弹窗 -->
    <van-popup v-model:show="showOrderDetailPopup" position="bottom" :style="{ height: '80%' }">
      <div class="order-detail-panel">
        <van-nav-bar title="订单详情" left-text="返回" left-arrow @click-left="showOrderDetailPopup = false" />
        <div v-if="selectedOrder" class="order-info">
          <!-- 基本信息 -->
          <van-cell title="订单编号" :value="selectedOrder.order_no" />
          <van-cell title="患者姓名" :value="selectedOrder.patient_name" />
          <van-cell title="科室" :value="selectedOrder.department" />
          <van-cell title="医生" :value="selectedOrder.doctor" />
          
          <!-- 就诊信息 -->
          <van-divider>就诊信息</van-divider>
          <van-cell title="预计就诊日期" :value="selectedOrder.visit_date" />
          <van-cell title="预计就诊时间段" :value="selectedOrder.time_slot" />
          <van-cell v-if="selectedOrder.visit_no" title="就诊序号" :value="selectedOrder.visit_no" />
          <van-cell v-if="selectedOrder.symptom && selectedOrder.symptom !== '-'" title="症状描述" :value="selectedOrder.symptom" />
          
          <!-- 费用信息 -->
          <van-divider>费用信息</van-divider>
          <van-cell title="订单金额" :value="`¥${selectedOrder.price}`" />
          <van-cell title="订单状态" :value="selectedOrder.status" />
          <van-cell title="支付状态" :value="selectedOrder.pay_status" />
          
          <!-- 时间信息 -->
          <van-divider>时间信息</van-divider>
          <van-cell title="订单创建时间" :value="selectedOrder.create_time" />
          <van-cell v-if="selectedOrder.pay_time && selectedOrder.pay_time !== '-'" title="支付时间" :value="selectedOrder.pay_time" />
          <van-cell v-if="selectedOrder.actual_visit_time && selectedOrder.actual_visit_time !== '-'" title="实际就诊时间" :value="selectedOrder.actual_visit_time" />
          <van-cell v-if="selectedOrder.cancel_time && selectedOrder.cancel_time !== '-'" title="取消时间" :value="selectedOrder.cancel_time" />
          <van-cell v-if="selectedOrder.update_time && selectedOrder.update_time !== '-'" title="最后更新时间" :value="selectedOrder.update_time" />
          
          <!-- 取消信息 -->
          <van-cell v-if="selectedOrder.cancel_reason" title="取消原因" :value="selectedOrder.cancel_reason" />
        </div>
        <!-- 操作按钮区域 -->
        <div v-if="selectedOrder && (selectedOrder.status === '待支付' || selectedOrder.status === '已支付')" class="order-actions">
          <van-button type="danger" block @click="onCancelFromDetail">取消预约</van-button>
          <van-button type="primary" block @click="onRescheduleFromDetail">改期预约</van-button>
        </div>
      </div>
    </van-popup>
    <!-- 取消预约弹窗 -->
    <van-popup v-model:show="showCancelPopup" position="bottom" :style="{ height: '50%' }">
      <div class="cancel-panel">
        <van-nav-bar title="取消预约" left-text="返回" left-arrow @click-left="showCancelPopup = false" />
        <div class="cancel-content">
          <van-field
            v-model="cancelReason"
            label="取消原因"
            type="textarea"
            placeholder="请简要说明取消原因"
            rows="3"
          />
          <div class="cancel-rules">
            <van-divider>退号规则</van-divider>
            <div class="rule-item">• 就诊前24小时取消，全额退款</div>
            <div class="rule-item">• 就诊前12-24小时取消，扣除20%手续费</div>
            <div class="rule-item">• 就诊前12小时内取消，扣除50%手续费</div>
            <div class="rule-item">• 就诊当天取消，不予退款</div>
          </div>
          <van-button type="danger" block @click="confirmCancel">确认取消</van-button>
        </div>
      </div>
    </van-popup>
    <!-- 改期预约弹窗 -->
    <van-popup v-model:show="showReschedulePopup" position="bottom" :style="{ height: '80%' }">
      <div class="reschedule-panel">
        <van-nav-bar title="改期预约" left-text="返回" left-arrow @click-left="showReschedulePopup = false" />
        <div class="reschedule-content">
          <van-cell title="原预计就诊时间" :value="`${selectedOrder?.visit_date} ${selectedOrder?.time_slot}`" />
          <van-divider>选择新时间</van-divider>
          
          <!-- 可用排班列表 -->
          <div v-if="availableSchedules.length > 0" class="available-schedules">
            <van-cell
              v-for="schedule in availableSchedules"
              :key="schedule.schedule_id"
              :title="formatScheduleDate(schedule.visit_date) + ' ' + formatTimeSlot(schedule.time_slot)"
              :label="`${schedule.start_time}-${schedule.end_time} | 剩余号源: ${schedule.remaining_quota} | 价格: ¥${schedule.price}`"
              @click="selectedScheduleId = schedule.schedule_id"
            >
              <template #right-icon>
                <van-radio 
                  :name="schedule.schedule_id" 
                  :model-value="selectedScheduleId"
                  @update:model-value="selectedScheduleId = schedule.schedule_id"
                />
              </template>
            </van-cell>
          </div>
          
          <!-- 无可用排班提示 -->
          <div v-else class="no-schedules">
            <van-empty description="暂无可用排班" />
          </div>
          
          <van-button 
            type="primary" 
            block 
            :disabled="!selectedScheduleId"
            @click="confirmReschedule"
          >
            确认改期
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { showFailToast,showConfirmDialog } from 'vant'
import { useRouter } from 'vue-router'
import axios from '../axios/axiosInstance';
import { useUserStore } from '../stores/user.js';
import { useRegisterStore } from '../stores/register.js'

const registerStore = useRegisterStore()
const userStore = useUserStore();
// 获取默认就诊人ID
const currentPatientId = computed(() => {
  return userStore.getDefaultPatient()?.patient_id || null;
});
// 获取当前用户ID
const currentUserId = computed(() => {
  return userStore.userInfo.user_id || null;
});


const router = useRouter();
const mainTab = ref(0);
const activeDeptIndex = ref(0);
const departments = ref([]);
const showDeptDetail = ref(false);
const deptDetail = ref({});
const showCalendar = ref(false);
const selectedDate = ref('');
const filterTime = ref('');
const onlyAvailable = ref(false);
const showDoctorDetailPage = ref(false);

// 获取科室数据
async function fetchDepartments() {
  try {
    const response = await axios.get('/api/v1/departments');
    if (response.data.code === 0) {
      departments.value = response.data.data;
    } else {
      console.error('获取科室失败:', response.data.message);
    }
  } catch (error) {
    console.error('请求科室数据失败:', error);
    // 使用模拟数据作为fallback
    departments.value = [
      {
        dept_id: 1,
        name: '内科',
        introduction: '负责内科疾病诊疗',
        children: [
          { dept_id: 6, name: '心内科', introduction: '内科下属，专注心脏疾病' },
          { dept_id: 7, name: '消化内科', introduction: '内科下属，专注消化系统疾病' },
          { dept_id: 8, name: '呼吸内科', introduction: '内科下属，专注呼吸系统疾病' },
        ]
      },
      {
        dept_id: 2,
        name: '外科',
        introduction: '负责外科手术及相关疾病',
        children: [
          { dept_id: 9, name: '普通外科', introduction: '外科下属，常见外科手术' },
          { dept_id: 10, name: '骨科', introduction: '外科下属，骨骼及关节疾病' },
        ]
      }
    ];
  }
}

// 获取科室医生数据
async function fetchDoctors(deptId) {
  try {
    const response = await axios.get(`/api/v1/department/${deptId}/doctor`);
    if (response.data.code === 0) {
      // 转换API返回的医生数据格式
      allDoctors.value = response.data.data.map(doctor => ({
        id: doctor.doctor_id,
        name: doctor.name,
        title: doctor.title,
        specialty: doctor.specialty,
        avatar: doctor.avatar || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
        time: '上午', // 默认时间，后续可从排班API获取
        available: true, // 默认有号，后续可从排班API获取
        deptId: deptId,
        desc: doctor.introduction || '暂无简介',
        visit_count: doctor.visit_count
      }));
    } else {
      console.error('获取医生失败:', response.data.message);
      allDoctors.value = [];
    }
  } catch (error) {
    console.error('请求医生数据失败:', error);
    // 使用模拟数据作为fallback
    allDoctors.value = [
      { id: 1, name: '王医生', title: '主任医师', specialty: '呼吸疾病', avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg', time: '上午', available: true, deptId: deptId, desc: '呼吸疾病专家' },
      { id: 2, name: '赵医生', title: '副主任医师', specialty: '哮喘', avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg', time: '下午', available: false, deptId: deptId, desc: '哮喘专科医生' },
    ];
  }
}

// 获取医生详情数据
async function fetchDoctorDetail(doctorId) {
  try {
    const response = await axios.get(`/api/v1/doctor/${doctorId}`);
    if (response.data.code === 0) {
      const doctor = response.data.data;
      doctorDetail.value = {
        id: doctor.doctor_id,
        name: doctor.name,
        title: doctor.title,
        specialty: doctor.specialty,
        avatar: doctor.avatar || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
        desc: doctor.introduction || '暂无简介',
        visit_count: doctor.visit_count
      };
      // showDoctorDetail.value = true; // This is now handled by showDoctorDetailPage
    } else {
      console.error('获取医生详情失败:', response.data.message);
    }
  } catch (error) {
    console.error('请求医生详情失败:', error);
    // 使用当前医生数据作为fallback
    const currentDoctor = allDoctors.value.find(doc => doc.id === doctorId);
    if (currentDoctor) {
      doctorDetail.value = currentDoctor;
      // showDoctorDetail.value = true; // This is now handled by showDoctorDetailPage
    }
  }
}

// 日期一行：生成接下来一周，并默认选中今天
const weekDates = computed(() => {
  const arr = [];
  const today = new Date();
  for (let i = 0; i < 7; i++) {
    const d = new Date(today.getFullYear(), today.getMonth(), today.getDate() + i);
    arr.push({
      value: `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`,
      label: ['日','一','二','三','四','五','六'][d.getDay()],
      text: `${d.getMonth() + 1}/${d.getDate()}`,
      disabled: false
    });
  }
  return arr;
});

// 默认选中今天
if (!selectedDate.value) {
  const today = new Date();
  selectedDate.value = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
}

// 获取所有医生的排班（按当前日期）
async function fetchAllDoctorsSchedule(doctors, dateStr) {
  if (!doctors.length) return;
  const scheduleMap = {};
  await Promise.all(doctors.map(async doc => {
    try {
      const res = await axios.get(`/api/v1/doctor/${doc.id}/schedule`);
      if (res.data.code === 0) {
        // 只保留当前日期的排班
        scheduleMap[doc.id] = res.data.data.filter(sch => {
          const schDate = `${new Date(sch.visit_date).getFullYear()}-${new Date(sch.visit_date).getMonth() + 1}-${new Date(sch.visit_date).getDate()}`;
          return schDate === dateStr;
        });
      } else {
        scheduleMap[doc.id] = [];
      }
    } catch {
      scheduleMap[doc.id] = [];
    }
  }));
  doctorSchedulesMap.value = scheduleMap;
}

// 响应日期变化，刷新所有医生排班
watch(selectedDate, async (val) => {
  if (showDeptDetail.value && allDoctors.value.length) {
    await fetchAllDoctorsSchedule(allDoctors.value, val);
  }
});

// 在科室详情弹窗打开时，拉取所有医生排班（默认今天）
async function onDeptDetail(dept) {
  deptDetail.value = dept;
  showDeptDetail.value = true;
  // 获取该科室的医生列表
  await fetchDoctors(dept.dept_id);
  // 拉取所有医生的排班（默认今天）
  await fetchAllDoctorsSchedule(allDoctors.value, selectedDate.value);
}

// 判断医生在当前选中日期下是否有剩余号源
function hasAvailableScheduleForDate(doctorId) {
  const schedules = doctorSchedulesMap.value[doctorId] || [];
  return schedules.some(sch => {
    if (filterTime.value && formatTimeSlot(sch.time_slot) !== filterTime.value) return false;
    return sch.remaining_quota > 0;
  });
}

// 医生列表（初始为空，通过API获取）
const allDoctors = ref([]);

// 过滤医生列表，结合排班、只看有号和当前日期
const filteredDoctorsWithSchedule = computed(() => {
  if (!deptDetail.value.dept_id) return [];
  return allDoctors.value.filter(doc => {
    if (doc.deptId !== deptDetail.value.dept_id) return false;
    if (onlyAvailable.value && !hasAvailableScheduleForDate(doc.id)) return false;
    return true;
  });
});
// 判断医生是否有可用排班
function hasAvailableSchedule(doctorId) {
  return doctorSchedulesMap.value[doctorId]?.some(sch => {
    if (filterTime.value && formatTimeSlot(sch.time_slot) !== filterTime.value) return false;
    return sch.remaining_quota > 0;
  });
}
// 医生id到排班的映射（响应式）
const doctorSchedulesMap = ref({});

// 根据筛选条件过滤医生排班
const filteredSchedules = computed(() => {
  if (!filterTime.value) return doctorSchedules.value;
  
  return doctorSchedules.value.filter(schedule => {
    const timeSlot = schedule.time_slot;
    if (filterTime.value === '上午' && timeSlot === 1) return true;
    if (filterTime.value === '下午' && timeSlot === 2) return true;
    return false;
  });
});

const showDoctorDetail = ref(false);
const doctorDetail = ref({});
const doctorSchedules = ref([]);

// 订单管理相关变量
const selectedOrder = ref(null);
const showOrderDetailPopup = ref(false);
const showCancelPopup = ref(false);
const showReschedulePopup = ref(false);
const cancelReason = ref('');
const rescheduleDate = ref('');
const rescheduleTime = ref('');
const showRescheduleCalendar = ref(false);
const availableSchedules = ref([]); // 新增：可用排班列表
const selectedScheduleId = ref(null); // 新增：选中的排班ID

// 获取医生排班数据
async function fetchDoctorSchedule(doctorId) {
  try {
    const response = await axios.get(`/api/v1/doctor/${doctorId}/schedule`);
    
    if (response.data.code === 0) {
      // 正确赋值API返回的排班数组
      doctorSchedules.value = response.data.data;
    } else {
      console.error('获取医生排班失败:', response.data.message);
      doctorSchedules.value = [];
    }
  } catch (error) {
    console.error('请求医生排班失败:', error);
    doctorSchedules.value = [];
  }
}


// 格式化排班日期
function formatScheduleDate(dateString) {
  const date = new Date(dateString);
  return `${date.getMonth() + 1}/${date.getDate()}`;
}

// 格式化时间段
function formatTimeSlot(timeSlot) {
  return timeSlot === 1 ? '上午' : '下午';
}


async function onScheduleSelect(schedule) {
  try {
    const defaultPatient = userStore.getDefaultPatient();
    if (!defaultPatient || !defaultPatient.patient_id) {
      showFailToast('请先设置默认就诊人');
      router.push({
        path: '/patientManagement',
        query: { from: 'register' }
      });
      return;
    }

    const res = await axios.get(`/api/v1/schedule/${schedule.schedule_id}/available`);
    if (res.data.code === 0 && res.data.data.available) {
      const orderRes = await axios.post('/api/v1/payment/create', {
        user_id: currentUserId.value,
        patient_id: defaultPatient.patient_id,
        doctor_id: doctorDetail.value.id,
        dept_id: deptDetail.value.dept_id,
        schedule_id: schedule.schedule_id,
        visit_date: schedule.visit_date,
        time_slot: schedule.time_slot,
        amount: schedule.price,
        pay_type: 1,
        symptoms: '待补充'
      });
      
	  console.log('测试code',orderRes)
      if (orderRes.data.code === 0) {
        // 保存完整的API响应数据到Pinia，包含两个表的信息
        registerStore.setSelectedSchedule(schedule);
        registerStore.setOrderData({
          order: orderRes.data.data.order,       // 订单表信息
          payment: orderRes.data.data.payment,   // 支付表信息
          doctor: doctorDetail.value,
          schedule: schedule,
          department: deptDetail.value.name
        });
        
        // 跳转到支付页面，传递record_id
		
		console.log("这是order_id",orderRes.data.data.order.order_id)
        router.push({
          path: '/registerPay',
          query: { 
            orderId: orderRes.data.data.order.order_id,
            recordId: orderRes.data.data.payment.record_id  
          }
        });
      } else {
		  
        showConfirmDialog({
                  title: '系统提示',
                  message: '系统暂停挂号服务，请于线下挂号',
                  confirmButtonText: '确定',
                  showCancelButton: false
                }).then(() => {
                  router.push('/home');
                });
              
		console.log("创建订单失败")
      }
    } else {
		//用弹窗展示该时间段无号源，请选择其他时间，点击确认，就刷新页面，没有取消按钮
      showConfirmDialog({
              title: '提示',
              message: '该时间段无号源，请选择其他时间',
              confirmButtonText: '确定',
              showCancelButton: false
            }).then(() => {
              // 刷新当前页面
              window.location.reload();
            });
	  console.log("该时间段无号源")
    }
  } catch (error) {
    console.error('预约失败:', error);
    showFailToast('网络异常，请检查连接后重试');
  }
}





function onDoctorDetail(doc) {
  // 获取医生详细信息和排班
  fetchDoctorDetail(doc.id);
  fetchDoctorSchedule(doc.id);
}

const orderTabActive = ref(0);
const orderLoading = ref(false);
const orderFinished = ref(true);

// 订单列表（由API填充）
const orders = ref([]);

function mapOrderStatus(statusNum) {
  // 根据数据库字段定义：0-待支付，1-已支付，2-已取消，3-已完成
  if (statusNum === 0) return '待支付';
  if (statusNum === 1) return '已支付';
  if (statusNum === 2) return '已取消';
  if (statusNum === 3) return '已完成';
  return '未知';
}
function formatDateYMD(dateStr) {
  if (!dateStr) return '';
  try {
    const d = new Date(dateStr);
    if (isNaN(d.getTime())) return '';
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
  } catch (error) {
    console.error('日期格式化错误:', error, dateStr);
    return '';
  }
}

function formatDateTime(dateStr) {
  if (!dateStr) return '';
  try {
    const d = new Date(dateStr);
    if (isNaN(d.getTime())) return '';
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hour = String(d.getHours()).padStart(2, '0');
    const minute = String(d.getMinutes()).padStart(2, '0');
    return `${y}-${m}-${day} ${hour}:${minute}`;
  } catch (error) {
    console.error('日期时间格式化错误:', error, dateStr);
    return '';
  }
}

function formatVisitTime(visit_date, time_slot) {
  const day = formatDateYMD(visit_date);
  const slot = time_slot === 1 ? '上午' : '下午';
  return `${day} ${slot}`;
}

async function fetchOrders(status = null) {
  try {
    orderLoading.value = true;
    // 构建请求参数
    const params = {};
    params.user_id = currentUserId.value;
    if (status !== null) {
      params.order_status = status;
    }
    
    const res = await axios.get('/api/v1/registration', { params });
    if (res.data.code === 0 && Array.isArray(res.data.data)) {
      orders.value = res.data.data.map(o => {
        return {
          id: o.order_id,
          order_no: o.order_no,
          department: o.dept_name,
          doctor: o.doctor_name,
          doctor_id: o.doctor_id || o.doctorId, // 尝试多个可能的字段名
          schedule_id: o.schedule_id, // 添加排班ID字段
          visit_date: formatDateYMD(o.visit_date), // 预计就诊日期
          time_slot: formatTimeSlot(o.time_slot), // 时间段（上午/下午）
          create_time: o.create_time ? formatDateTime(o.create_time) : '-',
          cancel_time: o.cancel_time ? formatDateTime(o.cancel_time) : '-',
          finish_time: o.visit_time ? formatDateTime(o.visit_time) : '-',
          status: mapOrderStatus(o.order_status),
          price: o.amount || 0,
          symptom: o.symptoms || '-',
          patient_name: o.patient_name || '-', // 新增患者姓名
          visit_no: o.visit_no || '-', // 新增就诊号
          pay_status: o.pay_status === 1 ? '已支付' : '未支付', // 新增支付状态
          pay_time: o.pay_time ? formatDateTime(o.pay_time) : '-', // 新增支付时间
          actual_visit_time: o.visit_time ? formatDateTime(o.visit_time) : '-', // 实际就诊时间
          update_time: o.update_time ? formatDateTime(o.update_time) : '-', // 新增最后更新时间
          cancel_reason: o.cancel_reason || '' // 新增取消原因
        };
      });
    } else {
      orders.value = [];
    }
  } catch (e) {
    orders.value = [];
  } finally {
    orderLoading.value = false;
    orderFinished.value = true;
  }
}

// 根据状态筛选订单（改为纯前端筛选，不触发API请求）
function filteredOrders(status) {
  return orders.value.filter(order => order.status === status);
}

// 进入"挂号管理"Tab时拉取所有订单
watch(mainTab, (val) => {
  if (val === 1) {
    fetchOrders(); // 不传status，获取所有订单
  }
});

// 切换订单状态Tab时重新请求对应状态的订单
watch(orderTabActive, (val) => {
  if (mainTab.value === 1) { // 确保在挂号管理Tab
    let statusNum;
    if (val === 0) statusNum = 0; // 待支付
    else if (val === 1) statusNum = 1; // 已支付
    else if (val === 2) statusNum = 3; // 已完成
    else if (val === 3) statusNum = 2; // 已取消
    fetchOrders(statusNum);
  }
});

// 显示订单详情
async function showOrderDetail(order) {
  try {
    // 获取订单详情
    const res = await axios.get(`/api/v1/registration/${order.id}`);
    const data = res.data;
    
    if (data.code === 0 && data.data) {
      const detail = data.data;
      selectedOrder.value = {
        id: detail.order_id,
        order_no: detail.order_no,
        department: detail.dept_name,
        doctor: detail.doctor_name,
        doctor_id: detail.doctor_id || detail.doctorId, // 尝试多个可能的字段名
        schedule_id: detail.schedule_id, // 添加排班ID字段
        patient_name: detail.patient_name,
        visit_date: formatDateYMD(detail.visit_date), // 预计就诊日期
        time_slot: formatTimeSlot(detail.time_slot), // 时间段（上午/下午）
        visit_no: detail.visit_no,
        create_time: detail.create_time ? formatDateTime(detail.create_time) : '-',
        cancel_time: detail.cancel_time ? formatDateTime(detail.cancel_time) : '-',
        pay_time: detail.pay_time ? formatDateTime(detail.pay_time) : '-',
        status: mapOrderStatus(detail.order_status),
        price: detail.amount || 0,
        symptom: detail.symptoms || '-',
        pay_status: detail.pay_status === 1 ? '已支付' : '未支付',
        actual_visit_time: detail.visit_time ? formatDateTime(detail.visit_time) : '-', // 实际就诊时间
        update_time: detail.update_time ? formatDateTime(detail.update_time) : '-', // 最后更新时间
        cancel_reason: detail.cancel_reason || '' // 取消原因
      };
    } else {
      // 如果获取详情失败，使用列表中的基础信息
      selectedOrder.value = order;
    }
    
    showOrderDetailPopup.value = true;
  } catch (error) {
    console.error('获取订单详情失败:', error);
    // 使用列表中的基础信息作为fallback
    selectedOrder.value = order;
    showOrderDetailPopup.value = true;
  }
}

// 取消预约
function onCancel(order) {
  selectedOrder.value = order;
  showCancelPopup.value = true;
}

// 取消预约 (从详情弹窗)
function onCancelFromDetail() {
  showOrderDetailPopup.value = false;
  showCancelPopup.value = true;
}

// 改期预约 (从详情弹窗)
async function onRescheduleFromDetail() {
  showOrderDetailPopup.value = false;
  showReschedulePopup.value = true;
  
  // 获取该医生的可用排班
  if (selectedOrder.value && selectedOrder.value.doctor_id) {
    await fetchAvailableSchedules(selectedOrder.value.doctor_id);
  } else {
    console.error('无法获取医生ID，无法获取可用排班');
    availableSchedules.value = [];
  }
}

// 确认取消
async function confirmCancel() {
  if (!cancelReason.value.trim()) {
    alert('请填写取消原因');
    return;
  }
  
  try {
    // 调用取消预约API
    const params = {};
    params.user_id = currentUserId.value;
    
    const res = await axios.post(`/api/v1/registration/${selectedOrder.value.id}/cancel`, {}, { params });
    
    const data = res.data;
    if (data.code === 0) {
      alert('取消预约成功');
      showCancelPopup.value = false;
      cancelReason.value = '';
      
      // 刷新订单列表
      await fetchOrders();
    } else {
      alert(data.message || '取消预约失败');
    }
  } catch (error) {
    console.error('取消预约失败:', error);
    alert('取消预约失败，请重试');
  }
}

// 改期预约
async function onReschedule(order) {
  selectedOrder.value = order;
  showReschedulePopup.value = true;
  
  // 通过订单详情获取医生信息
  try {
    const res = await axios.get(`/api/v1/registration/${order.id}`);
	console.log(res)
    if (res.data.code === 0 && res.data.data) {
      const detail = res.data.data;
      if (detail.doctor_id) {
        await fetchAvailableSchedules(detail.doctor_id);
      } else {
        console.error('订单详情中没有医生ID');
        availableSchedules.value = [];
      }
    } else {
      console.error('获取订单详情失败');
      availableSchedules.value = [];
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    availableSchedules.value = [];
  }
}

// 获取可用排班
async function fetchAvailableSchedules(doctorId) {
  try {
    const res = await axios.get(`/api/v1/doctor/${doctorId}/schedule`);
    if (res.data.code === 0) {
      // 过滤出有剩余号源的排班
      availableSchedules.value = res.data.data.filter(schedule => 
        schedule.remaining_quota > 0
      );
    } else {
      availableSchedules.value = [];
    }
  } catch (error) {
    console.error('获取可用排班失败:', error);
    availableSchedules.value = [];
  }
}

// 选择改期日期
function onRescheduleDateConfirm(date) {
  rescheduleDate.value = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  showRescheduleCalendar.value = false;
}

// 确认改期
async function confirmReschedule() {
  if (!selectedScheduleId.value) {
    alert('请选择新的就诊时间');
    return;
  }
  
  try {
    // 获取选中的排班信息
    const selectedSchedule = availableSchedules.value.find(s => s.schedule_id == selectedScheduleId.value);
    if (!selectedSchedule) {
      alert('未找到选中的排班信息');
      return;
    }
    
    // 调用改期API
    const params = {};
    params.new_schedule_id = selectedScheduleId.value;
    params.user_id = currentUserId.value;
    params.visit_date = selectedSchedule.visit_date; // 添加就诊日期
    params.time_slot = selectedSchedule.time_slot; // 添加时间段
    
    const res = await axios.post(`/api/v1/registration/${selectedOrder.value.id}/reschedule`, {}, { params });
    
    const data = res.data;
    if (data.code === 0) {
      alert('改期成功');
      showReschedulePopup.value = false;
      rescheduleDate.value = '';
      rescheduleTime.value = '';
      selectedScheduleId.value = null;
      
      // 刷新订单列表
      await fetchOrders();
    } else {
      alert(data.message || '改期失败');
    }
  } catch (error) {
    console.error('改期失败:', error);
    alert('改期失败，请重试');
  }
}

// 页面加载时获取科室数据
onMounted(() => {
  fetchDepartments();
});

function onDoctorDetailPage(doc) {
  fetchDoctorDetail(doc.id);
  fetchDoctorSchedule(doc.id);
  showDoctorDetailPage.value = true;
}
</script>

<style scoped>
.dept-select-container {
  display: flex;
  height: 70vh;
}
.sidebar {
  width: 90px;
  border-right: 1px solid #f0f0f0;
}
.subdept-panel {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
}
.dept-detail-panel {
  padding: 12px;
}
.dept-info {
  margin-bottom: 12px;
}
.dept-title {
  font-size: 18px;
  font-weight: bold;
}
.dept-desc {
  color: #888;
  font-size: 14px;
  margin-top: 4px;
}
.date-row-scroll {
  display: flex;
  overflow-x: auto;
  margin-bottom: 8px;
  gap: 4px;
}
.date-item {
  min-width: 38px;
  padding: 2px 0;
  text-align: center;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
  background: #fafbfc;
  cursor: pointer;
  user-select: none;
  font-size: 12px;
  line-height: 1.2;
}
.date-item.active {
  background: #1989fa;
  color: #fff;
  border-color: #1989fa;
}
.date-item.disabled {
  color: #ccc;
  pointer-events: none;
  background: #f5f5f5;
}
.filter-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 8px 0;
  padding: 8px 0;
}
.doctor-filter-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 8px 0 4px 0;
  padding: 4px 0;
}
.doctor-filter-left {
  flex: 1;
  display: flex;
  justify-content: flex-start;
}
.doctor-filter-center {
  flex: 1;
  text-align: center;
}
.doctor-filter-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}
.doctor-filter-row-compact {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  margin: 8px 0 4px 0;
  padding: 4px 0;
  font-size: 13px;
}
.doctor-filter-radio {
  font-size: 13px;
}
.doctor-filter-checkbox {
  font-size: 13px;
  margin-left: 12px;
}
.van-radio__label, .van-checkbox__label {
  font-size: 13px !important;
}
.van-radio {
  font-size: 13px !important;
}
.doctor-detail-panel {
  padding: 16px;
}
.doctor-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}
.doctor-name {
  font-size: 16px;
  font-weight: bold;
}
.doctor-specialty {
  font-size: 14px;
  color: #666;
}
.doctor-visit {
  font-size: 14px;
  color: #666;
}
.doctor-desc {
  font-size: 14px;
  color: #333;
  margin-top: 8px;
}
.schedule-list {
  max-height: 400px;
  overflow-y: auto;
}
.schedule-price {
  color: #e54d42;
  font-weight: bold;
  font-size: 15px;
}
.doctor-detail-page {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 24px;
}
.doctor-info-block {
  display: flex;
  align-items: center;
  padding: 24px 16px 8px 16px;
  background: #f7f8fa;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 2px 8px #f0f1f3;
}
.doctor-avatar {
  margin-right: 18px;
  border: 2px solid #e54d42;
}
.doctor-main-info {
  flex: 1;
}
.doctor-name {
  font-size: 22px;
  font-weight: 700;
  color: #222;
  margin-bottom: 2px;
}
.doctor-title {
  font-size: 16px;
  color: #1989fa;
  margin-bottom: 2px;
}
.doctor-specialty {
  font-size: 14px;
  color: #666;
  margin-bottom: 2px;
}
.doctor-visit {
  font-size: 13px;
  color: #e54d42;
  margin-bottom: 2px;
}
.doctor-desc {
  font-size: 15px;
  color: #333;
  margin: 8px 16px 16px 16px;
}
.schedule-list {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 8px;
}
.schedule-price {
  color: #e54d42;
  font-weight: bold;
  font-size: 15px;
}
.schedule-available-tag {
  margin-right: 6px;
  font-size: 10px !important;
  height: 18px;
  line-height: 16px;
  padding: 0 4px;
}
.schedule-appoint-btn {
  font-size: 16px !important;
  font-weight: bold;
  padding: 0 18px;
  height: 32px;
  border-radius: 18px;
}
.doctor-detail-nested {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 24px;
}
.order-detail-panel {
  padding: 16px;
}
.order-info {
  margin-top: 16px;
}
.order-actions {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.cancel-panel, .reschedule-panel {
  padding: 16px;
}
.cancel-content, .reschedule-content {
  margin-top: 16px;
}
.cancel-rules {
  margin: 16px 0;
  padding: 12px;
  background: #f7f8fa;
  border-radius: 8px;
}
.rule-item {
  font-size: 14px;
  color: #666;
  margin: 4px 0;
}
.available-schedules {
  max-height: 300px;
  overflow-y: auto;
  margin: 16px 0;
}
.no-schedules {
  padding: 40px 0;
  text-align: center;
}
</style>